﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Net;
using System.Web.UI.HtmlControls;
using Gift.Model;
using Gift.WebApp;

namespace WebApp.admin.goods
{
    public partial class goodsSpecifications : BaseAdmin
    {

        tbSpecifications oSpecifications;
        tbSpecificationsValue oSpecificationsValue;
        HttpFileCollection files;
        string _picShow = "none";

        public string PicShow
        {
            get { return _picShow; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (base.Request.QueryString["ot"] == "ed")
                {
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.GoodsSpecificationsEdit);
                }
                else
                {
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.GoodsSpecificationsAdd);
                }
                this.BuildForm();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if ((base.Request.QueryString["ot"] == "ed") && (base.Request.QueryString["id"] != null))
            {
                int id = int.Parse(base.Request.QueryString["id"]);
                try
                {
                    DataTable dtSpecValues = BaseFactory.theSpecificationsValue.GetSpecificationsValueBySpecifications(id);
                    if (dtSpecValues != null && dtSpecValues.Rows.Count > 0)
                    {

                        string[] arrSourcePics = Request.Form["specImages"].Split(',');
                        foreach (DataRow dr in dtSpecValues.Rows)
                        {
                           if(!arrSourcePics.Contains(dr["id"].ToString()))
                            {
                                try
                                {
                                    File.Delete(Server.MapPath(dr["specificationsValueImage"].ToString()));
                                }
                                catch
                                { }
                                BaseFactory.theSpecificationsValue.Delete(int.Parse(dr["id"].ToString()));
                            }
                        }
                    }

                    oSpecifications = BaseFactory.theSpecifications.GetModel(id);
                    oSpecifications.specificationsName = this.txtSpecificationsName.Value.Trim();
                    oSpecifications.specificationsType = int.Parse(base.Request.Form["specificationsType"]);
                    oSpecifications.showType = int.Parse(base.Request.Form["showType"]);
                    oSpecifications.remark = this.txtRemark.Value.Trim();
                  
                    if (BaseFactory.theSpecifications.Update(oSpecifications))
                    {
                        if (base.Request.Form["specificationsType"] == "0")
                        {
                            string[] arrSpecifications = Request.Form["SpecificationsValue"].Split(',');
                            foreach (string spec in arrSpecifications)
                            {
                                oSpecificationsValue = new tbSpecificationsValue();
                                oSpecificationsValue.specifications = id;
                                oSpecificationsValue.specificationsValueName = spec;
                                BaseFactory.theSpecificationsValue.Add(oSpecificationsValue);
                            }
                        }
                        else
                        {
                            string[] arrSpecifications = Request.Form["SpecificationsValue"].Split(',');
                            string[] arrImage = Request.Form["FileSVimage"].Split(',');
                            for (int i = 0; i < arrImage.Length; i++)
                            {
                                if (arrImage[i].Length > 1)
                                {
                                    oSpecificationsValue = new tbSpecificationsValue();
                                    oSpecificationsValue.specifications = id;
                                    oSpecificationsValue.specificationsValueName = arrSpecifications[i];
                                    oSpecificationsValue.specificationsValueImage = "/cn/specifications_value/" + this.UpLoadFile(arrImage[i], Server.MapPath("/cn/specifications_value/"), true);
                                    BaseFactory.theSpecificationsValue.Add(oSpecificationsValue);
                                }
                            }
                        }
                    }
                    base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"更新成功！\");window.location.href='goodsSpecificationsList.aspx'; </script>");
                }
                catch
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"更新失败！\");</script>");
                }


            }
            else
            {
                try
                {
                    oSpecifications = new tbSpecifications();
                    oSpecifications.specificationsName = this.txtSpecificationsName.Value.Trim();
                    oSpecifications.specificationsType = int.Parse(base.Request.Form["specificationsType"]);
                    oSpecifications.showType = int.Parse(base.Request.Form["showType"]);
                    oSpecifications.remark = this.txtRemark.Value.Trim();

                    oSpecifications.CompanyId = int.Parse(base.Administrator.CompanyId);
                    int id = BaseFactory.theSpecifications.Add(oSpecifications);
                    if (id > 0)
                    {
                        if (base.Request.Form["specificationsType"] == "0")
                        {
                            string[] arrSpecifications = Request.Form["SpecificationsValue"].Split(',');
                            foreach (string spec in arrSpecifications)
                            {
                                oSpecificationsValue = new tbSpecificationsValue();
                                oSpecificationsValue.specifications = id;
                                oSpecificationsValue.specificationsValueName = spec;
                                BaseFactory.theSpecificationsValue.Add(oSpecificationsValue);
                            }
                        }
                        else
                        {
                            string[] arrSpecifications = Request.Form["SpecificationsValue"].Split(',');
                            string[] arrImage = Request.Form["FileSVimage"].Split(',');
                            files = HttpContext.Current.Request.Files;
                            for (int i = 0; i < arrImage.Length; i++)
                            {
                                oSpecificationsValue = new tbSpecificationsValue();
                                oSpecificationsValue.specifications = id;
                                oSpecificationsValue.specificationsValueName = arrSpecifications[i];
                                oSpecificationsValue.specificationsValueImage = "/cn/specifications_value/" +  this.UpLoadFile(arrImage[i], Server.MapPath("/cn/specifications_value/"), true);
                                //if (files[i].FileName != "")
                                //{
                                //    oSpecificationsValue.specificationsValueImage = "/cn/specifications_value/" + DateTime.Now.ToString("yyyyMMddHHssmmffffff") + Path.GetExtension(arrImage[i]);
                                //    files[i].SaveAs(oSpecificationsValue.specificationsValueImage);
                                //}
                               // oSpecificationsValue.specificationsValueImage = arrImage[i];
                                BaseFactory.theSpecificationsValue.Add(oSpecificationsValue);
                            }
                        }
                    }

                    base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"添加成功！\");window.location.href='goodsSpecificationsList.aspx';</script>");
                }

                catch
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"添加失败！\");</script>");
                }
            }
          
        }

        /**/
        ///   <summary> 
        /// WebClient上传文件至服务器
        ///   </summary> 
        ///   <param name="fileNamePath"> 文件名，全路径格式 </param> 
        ///   <param name="uriString"> 服务器文件夹路径 </param> 
        ///   <param name="IsAutoRename"> 是否自动按照时间重命名 </param> 
        public string UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
        {
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            string NewFileName = fileName;
            if (IsAutoRename)
            {
                NewFileName = DateTime.Now.ToString("yyyyMMddHHssmmffffff")  + Path.GetExtension(fileNamePath);
            }

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (uriString.EndsWith("\\") == false) uriString = uriString + "\\";

            uriString = uriString + NewFileName;
            //Utility.LogWriter log = new Utility.LogWriter();
            // log.AddLog(uriString, "Log");
            // log.AddLog(fileNamePath, "Log"); 
            /**/
            /**/
            /**/
            /// 创建WebClient实例 
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            // 要上传的文件 
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            // FileStream fs = OpenFile(); 
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, " PUT ");


            try
            {

                // 使用UploadFile方法可以用下面的格式
                // myWebClient.UploadFile(uriString,"PUT",fileNamePath); 


                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                   // log.AddLog(" 上传日志文件成功！ ", " Log ");
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();
                 //   log.AddLog(" 上传日志文件失败，文件不可写！ ", " Log ");
                }

            }
            catch (Exception err)
            {
                postStream.Close();
                fs.Dispose();
                // Utility.LogWriter log = new Utility.LogWriter(); 
             //   log.AddLog(err, " 上传日志文件异常！ ", " Log ");
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
            return NewFileName;
        } 


        void BuildForm()
        {
            if ((base.Request.QueryString["ot"] == "ed") && (base.Request.QueryString["id"] != null))
            {
                int id = int.Parse(base.Request.QueryString["id"]);
                oSpecifications = BaseFactory.theSpecifications.GetModel(id);
                this.txtSpecificationsName.Value = oSpecifications.specificationsName;
                if (oSpecifications.specificationsType == 0)
                {
                    this.rdSpecificationsType.Checked = true;
                    this.rdSpecificationsType1.Checked = false;
                }
                else
                {
                    this.rdSpecificationsType.Checked = false;
                    this.rdSpecificationsType1.Checked = true;
                }
                if (oSpecifications.showType == 0)
                {
                    this.rdShowType.Checked = true;
                    this.rdShowType1.Checked = false;
                }
                else
                {
                    this.rdShowType.Checked = false;
                    this.rdShowType1.Checked = true;
                }
                this.txtRemark.Value = oSpecifications.remark;

                DataTable dtSpecValues = BaseFactory.theSpecificationsValue.GetSpecificationsValueBySpecifications(id);
                if (dtSpecValues != null && dtSpecValues.Rows.Count > 0)
                {
                    if (oSpecifications.specificationsType == 0)
                    {
                        int iRow = 0;
                        foreach (DataRow dr in dtSpecValues.Rows)
                        {
                            iRow++;
                            HtmlTableRow tRow = new HtmlTableRow();
                            HtmlTableCell tCell = new HtmlTableCell();
                            tCell.InnerHtml = "<input name=\"specificationsValue\" type=\"text\" value=\"" + dr["specificationsValueName"].ToString() + "\" />";
                            tRow.Cells.Add(tCell);
                            HtmlTableCell tCell1 = new HtmlTableCell();
                            tCell1.InnerHtml = "";
                            tRow.Cells.Add(tCell1);
                            HtmlTableCell tCel2 = new HtmlTableCell();
                            tCel2.InnerHtml = "<input type=button class=\"formButton\" value=\"删除\" title=\"删除规格值\" onclick=\"delSVInput(this.parentNode.parentNode.rowIndex);\">";
                            tRow.Cells.Add(tCel2);
                            this.SpecificationsValues.Rows.Add(tRow);

                        }
                    }
                    else
                    {
                        _picShow = "inline";
                        int iRow = 0;
                        foreach (DataRow dr in dtSpecValues.Rows)
                        {
                            iRow++;
                            HtmlTableRow tRow = new HtmlTableRow();
                            HtmlTableCell tCell = new HtmlTableCell();
                            tCell.InnerHtml = "<input name=\"specificationsValue\" type=\"text\" value=\"" + dr["specificationsValueName"].ToString() + "\" />";
                            tRow.Cells.Add(tCell);
                            HtmlTableCell tCell1 = new HtmlTableCell();
                            tCell1.InnerHtml = "<div class=\"specificationValueImagePreview\" id=\"imgDiv" + iRow + "\"><img name='imageShows' id='img" + dr["id"].ToString() + "'  src='" + dr["specificationsValueImage"].ToString() + "' /></div>"
                                + " <input name=\"specImages\" type=\"hidden\" value=\"" + dr["id"].ToString() + "\" />"
                                + " <input class=\"specificationValueImageUploadButton\" id=\"imgfile" + iRow + "\" name=\"fileSVimage\" type=\"file\" onchange=\"fileupload('#imgfile" + iRow + "','#imgDiv" + iRow + "');\"/><span class=\"imgClass\">图片大小：30*30 分辨率：72像素 格式：jpg,bmp,gif,png</sapn>";
                            tRow.Cells.Add(tCell1);
                            HtmlTableCell tCel2 = new HtmlTableCell();
                            tCel2.InnerHtml = "<input type=button class=\"formButton\" value=\"删除\" title=\"删除规格值\" onclick=\"delSVInput(this.parentNode.parentNode.rowIndex);\">";
                            tRow.Cells.Add(tCel2);
                            this.SpecificationsValues.Rows.Add(tRow);
                        }
                    }
                }
            }
          }
    }
}